package com.example.extra.service.lmpl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.extra.config.MinioConfig;
import com.example.extra.entity.ProductPdf;
import com.example.extra.mapper.ProductPdfMapper;
import com.example.extra.service.IProductPdfService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.UUID;

/**
 * <p>
 * 产品PDF表 服务实现类
 * </p>
 *
 * @author system
 * @since 2025-01-17
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ProductPdfServiceImpl extends ServiceImpl<ProductPdfMapper, ProductPdf> implements IProductPdfService {

    private final MinioClient minioClient;
    private final MinioConfig minioConfig;

    @Override
    public String uploadPdf(MultipartFile file, String createUserId,String catalogue,Integer storageType) {
        try {
            // 检查文件类型
            if (!file.getContentType().equals("application/pdf")) {
                throw new RuntimeException("只支持PDF文件格式");
            }

            // 检查文件大小（限制为50MB）
            if (file.getSize() > 50 * 1024 * 1024) {
                throw new RuntimeException("文件大小不能超过50MB");
            }

            // 确保存储桶存在
            ensureBucketExists();

            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString() + fileExtension;
            String filePath = catalogue + fileName;

            // 上传文件到MinIO
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(minioConfig.getBucketName())
                            .object(filePath)
                            .stream(file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build()
            );

            // 构建文件URL
            String fileUrl = minioConfig.getEndpoint() + "/" + minioConfig.getBucketName() + "/" + filePath;

            // 保存到数据库
            ProductPdf productPdf = new ProductPdf();
            productPdf.setPdfPath(filePath);
            productPdf.setPdfSize(file.getSize());
            productPdf.setPdfStatus(1);
            productPdf.setIdentifier(UUID.randomUUID().toString());
            productPdf.setStorageType(storageType);
            productPdf.setMinioBucketZk(minioConfig.getBucketName());
            productPdf.setCreateUserId(createUserId);
            productPdf.setCreateTime(LocalDateTime.now());

            this.save(productPdf);

            log.info("PDF文件上传成功: {}", fileUrl);
            return fileUrl;

        } catch (Exception e) {
            log.error("PDF文件上传失败", e);
            throw new RuntimeException("文件上传失败: " + e.getMessage());
        }
    }

    @Override
    public IPage<ProductPdf> getPdfPage(Integer page, Integer size, String createUserId,Integer storageType) {
        Page<ProductPdf> pageParam = new Page<>(page, size);
        QueryWrapper<ProductPdf> queryWrapper = new QueryWrapper<>();
        
        // 如果传入了createUserId，则按用户ID过滤
        if (createUserId != null && !createUserId.trim().isEmpty()) {
            queryWrapper.eq("create_user_id", createUserId);
        }
        if(!ObjectUtil.isEmpty(storageType)){
            queryWrapper.eq("storage_type", storageType);
        }
        
        // 只查询正常状态的文件
        queryWrapper.eq("pdf_status", 1);
        
        // 按创建时间倒序排列
        queryWrapper.orderByDesc("create_time");
        
        return this.page(pageParam, queryWrapper);
    }

    /**
     * 确保存储桶存在
     */
    private void ensureBucketExists() {
        try {
            boolean bucketExists = minioClient.bucketExists(
                    BucketExistsArgs.builder()
                            .bucket(minioConfig.getBucketName())
                            .build()
            );
            
            if (!bucketExists) {
                minioClient.makeBucket(
                        MakeBucketArgs.builder()
                                .bucket(minioConfig.getBucketName())
                                .build()
                );
                log.info("创建MinIO存储桶: {}", minioConfig.getBucketName());
            }
        } catch (Exception e) {
            log.error("检查或创建MinIO存储桶失败", e);
            throw new RuntimeException("MinIO存储桶操作失败: " + e.getMessage());
        }
    }
}
